import dynamic from 'next/dynamic';
import axios from 'axios';
import Seo from '@/core/components/Seo';
import Breadcrumb from '@/lib/category/components/Breadcrumb';

const BasicLayout = dynamic(
  () => import('@/core/components/layouts/BasicLayout'),
  { ssr: false }
);

const ProductSearch = dynamic(
  () => import('@/lib/product/components/ProductSearch'),
  { ssr: false }
);

export async function getServerSideProps(context) {
  const { slug } = context.query;

  if (!slug || typeof slug !== 'string') {
    return { notFound: true };
  }

  try {
    const res = await axios(
      `${process.env.NEXT_PUBLIC_SELF_HOST}/api/shop/searchkey?url=${slug}&from=searchkey`
    );

    const result = res?.data?.response?.docs?.[0];

    // 🔥 Kalau Solr gak ada data → 404
    if (!result) {
      return { notFound: true };
    }

    return {
      props: {
        result,
        slugRaw: slug,
      },
    };
  } catch (error) {
    return { notFound: true };
  }
}

export default function KeywordPage({ result, slugRaw }) {
  const readableSlug = decodeURIComponent(slugRaw)
    .replace(/-/g, ' ')
    .replace(/\b\w/g, (c) => c.toUpperCase());

  const ids = result?.product_ids_is || [];

  const query = {
    ids: ids.join(','),
    from: 'searchkey',
  };

  const categoryId =
    result?.category_id_i ||
    result?.public_categ_id_i ||
    (result?.category_ids_is && result?.category_ids_is[0]);

  const origin = (process.env.NEXT_PUBLIC_SELF_HOST || '').replace(/\/+$/, '');
  const url = `${origin}/searchkey/${slugRaw}`;

  return (
    <BasicLayout>
      <Seo
        title={`Beli ${readableSlug} Original & Harga Terjangkau - indoteknik.com`}
        description={`Beli ${readableSlug} Kirim Jakarta Surabaya Semarang Makassar Manado Denpasar.`}
        canonical={url}
        additionalMetaTags={[
          {
            name: 'keywords',
            content: `Beli ${readableSlug}, harga ${readableSlug}, ${readableSlug} murah`,
          },
        ]}
      />

      {categoryId && (
        <Breadcrumb
          categoryId={categoryId}
          currentLabel={readableSlug}
        />
      )}

      {ids.length > 0 && (
        <ProductSearch
          query={query}
          prefixUrl={`/searchkey/${slugRaw}`}
        />
      )}
    </BasicLayout>
  );
}